<template>
    <!--现场审核验收总结 en_std_eval_summary  evaluationSummary-->
    <Layout>
        <Form ref="queryForm" :model="dataToQuery" :label-width="120">
            <Row v-show="!switchFlag" class="query-form">
                <Col span="8">
                    <FormItem label="集团名称：" prop="belongOrgId">
                        <!--<cascader-dom class="query-form-el" ref='queryOrgCascader' @setOrgInfo='setQueryCompanyName' :orgTree="true" :setCurrentName="{label:dataToQuery.companyName,value:dataToQuery.companyId}"></cascader-dom>-->
                        <Select class='w' placeholder="集团名称"  v-model='dataToQuery.companyId'>
                            <Option v-for="item in twoLevel" :value="item.orgId" :key="item.orgId">{{item.orgName}}</Option>
                        </Select>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="年度：" prop="year" >
                        <DatePicker class="query-form-el" type="year" v-model="dataToQuery.year1" :clearable="false"
                                    @on-change="()=>{if(dataToQuery.year1 instanceof Date){dataToQuery.year = dataToQuery.year1.getFullYear().toString()}}"></DatePicker>
                    </FormItem>
                </Col>
                <Col span="8">
                    <Button @click="reset" class="ivu-btn-reset"  >重置</Button>
                    <Button type="primary" class="ivu-btn-query"   icon="md-search"  @click="query">查询</Button>
                </Col>
            </Row>
            <Row class="query-form">
                <Col span="24">
                    <Button size="large"  class="ivu-btn-add" icon="md-add"  @click="addInfo">新增</Button>
                </Col>
            </Row>
        </Form>
        <Table ref='table' :height="tableHeight"  no-data-text="没有查询到相关数据!" @on-selection-change = 'getSelectRows'
               border :columns="columns1"  :data="dataTable" >
        </Table>
        <Row style="margin-right:10px;">
            <Col span="24" >
                <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />
            </Col>
        </Row>
        <Modal :title="mode ==='view'? '标准化评定总结详情':'标准化评定总结'" :transfer=false :mask-closable="false" v-model="dialogShow" v-if="dataToView && dialogShow" :width=650 :styles="{height:'auto'}"  class-name='limit-height-dialog' >
            <Row>
                <Col span="24">
                    <Form ref="dialogForm" :class="mode === 'view'?'modal-view-detail':'modal-form'" :show-message="false" :model="dataToView" :rules="mode === 'view'?{} :ruleCustom"  :label-position="mode === 'view'?'right':'top'" :label-width="mode === 'view'?120:null">
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label="集团名称：" prop="belongOrgId">
                                    <div v-if="mode === 'view'">{{dataToView.belongOrgName}}</div>
                                    <!--<Input class="query-form-el" v-else v-model="dataToView.belongOrgName" readonly/>-->
                                    <Select v-else class='w' placeholder="集团名称"  v-model='dataToView.belongOrgId'  label-in-value @on-change="belongChange">
                                        <Option v-for="item in twoLevel" :value="item.orgId" :key="item.orgId">{{item.orgName}}</Option>
                                    </Select>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11" >
                                <FormItem label="年度：" prop="year" >
                                    <div v-if="mode === 'view'">{{dataToView.year}}</div>
                                    <DatePicker class="query-form-el" v-else type="year" placeholder="请输入" v-model="dataToView.yearDate"></DatePicker>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label="检查企业数量：" prop="checkNumCompany" >
                                    <div v-if="mode === 'view'">{{dataToView.checkNumCompany}}</div>
                                    <InputNumber class="query-form-el" :min="0" v-else type="text" v-model="dataToView.checkNumCompany"></InputNumber>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11" >
                                <FormItem label="检查开始时间：" prop="checkStartTime" >
                                    <div v-if="mode === 'view'">{{this.renderViewDate(dataToView.checkStartTime)}}</div>
                                    <DatePicker class="query-form-el" v-else v-model="dataToView.checkStartTime"
                                                :options="{disabledDate(date) {return date && dataToView.checkEndTime && date.valueOf() > dataToView.checkEndTime;}}"
                                                type="date" placeholder="请输入" ></DatePicker>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label="检查结束时间：" prop="checkEndTime" >
                                    <div v-if="mode === 'view'">{{this.renderViewDate(dataToView.checkEndTime)}}</div>
                                    <DatePicker class="query-form-el" v-else v-model="dataToView.checkEndTime"
                                                :options="{disabledDate(date) {return date && dataToView.checkStartTime && date.valueOf() < dataToView.checkStartTime;}}"
                                                type="date" placeholder="请输入" ></DatePicker>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem v-if="mode === 'view'" label="总结报告：">
                                    <div v-show="dataToView.idFiles.length>0" v-for="(item,index) in dataToView.idFiles">
                                        <a @click="downloadFiles(item,index)"><span style="color: #3399ff;margin-left: 5px">{{ item.fileName }}</span></a>
                                      <Progress  v-show="uploadListVisible[index]" :percent="uploadListPercent[index]"></Progress>
                                    </div>
                                </FormItem>
                                <FormItem v-else label="总结报告：">
                                    <div>
                                        <Upload ref="upload"
                                                :before-upload="(file) => { beforeUpload(file, 'id') }"
                                                :show-upload-list="true"
                                                :max-size="10240"
                                                multiple
                                                type="drag"
                                                :action="fileUrl">
                                            <div style="padding: 10px">
                                                <Icon type="ios-cloud-upload" size="45" style="color: #3399ff"></Icon>
                                                <p>点击将文件拖拽到这里上传</p>
                                                <span style="font-size:8px;color: #797a64">支持扩展名：.rar .zip .doc .docx .pdf...</span>
                                            </div>
                                        </Upload>
                                    </div>
                                    <div v-show="dataToView.idFiles.length>0" v-for="(item,index) in dataToView.idFiles" :key='item'>
                                        <a @click="downloadFiles(item,index)">{{ item.fileName }}</a>
                                        <Button type="text" icon="md-trash" @click="removeFile(item.id, 'id')" style="margin-left: 5px;margin-bottom: 3px"/>
                                      <Progress  v-show="uploadListVisible[index]" :percent="uploadListPercent[index]"></Progress>
                                    </div>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23" >
                                <FormItem label="总结简述：" prop="notes" >
                                    <div v-if="mode === 'view'">{{dataToView.notes}}</div>
                                    <Input class="query-form-el" v-else v-model="dataToView.notes" type="textarea" :rows="2" />
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span='11'>
                                <FormItem label="二级集团环保负责人：" prop="approvalUser">
                                    <div v-if="mode === 'view'">{{dataToView.approvalUserName}}</div>
                                    <Select v-else v-model="dataToView.approvalUser" :label-in-value="true" @on-change="charge">
                                        <Option v-for="item in chargeList" :value="item.userId" :key="item.userId">
                                            {{item.userName}}
                                        </Option>
                                    </Select>
                                </FormItem>
                            </Col>
                            <Col span='11'>
                                <FormItem :label="mode === 'view'?'集团审核人：':'选择集团审核人：'"  prop="aduitUser">
                                    <div v-if="mode === 'view'">{{dataToView.aduitUserName }}</div>
                                    <Select v-else class='w' placeholder="集团审核人" type='text' v-model='dataToView.aduitUser'>
                                        <Option v-for="item in aduitUserList" :value="item.userId" :key="item.userId">{{item.userName}}</Option>
                                    </Select>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='填报人：' prop='registrant'>
                                    <div v-if="mode === 'view'">{{dataToView.createUserName}}</div>
                                    <Input class="query-form-el" v-else type='text' v-model='dataToView.createUserName' readonly></Input>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='填报人手机号：' prop='registrantPhone'>
                                    <div v-if="mode === 'view'">{{dataToView.registrantPhone}}</div>
                                    <Input class="query-form-el" v-else type='text' v-model='dataToView.registrantPhone'></Input>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='填报时间：' prop='registTime'>
                                    <div v-if="mode === 'view'">{{renderViewDate(dataToView.registranTime)}}</div>
                                    <DatePicker v-else type="date" placeholder="请选择日期" class="query-form-el" v-model='dataToView.registranTime' readonly></DatePicker>
                                </FormItem>
                            </Col>
                            <Col span="11"></Col>
                        </Row>
                    </Form>
                </Col>
            </Row>
            <div slot="footer">
                <Button v-if="mode != 'view'" type="primary" :loading="pageStatus.sending" class='ivu-btn-save' @click="submit('dialogForm')" >确定</Button>
                <Button v-if="mode != 'view'" type="primary"  class='ivu-btn-cancel' @click="handleCancel" >取消</Button>
                <Button v-if="mode === 'view'" class='ivu-btn-save' @click="dialogShow=false">关闭</Button>
            </div>
        </Modal>

        <Modal :transfer=false v-model="model2" :width=500 title="审批" @on-cancel="model2=false;map={}">
            <Form ref="map" v-model="map" :label-width="120">
                <Row class="query-form">
                    <Col span="23">
                        <FormItem label='审批结果：'>
                            <Select v-model='map.approval'>
                                <Option value="2">通过</Option>
                                <Option value="3">退回</Option>
                            </Select>
                        </FormItem>
                    </Col>
                    <Col span="23">
                        <FormItem label='审批意见：' prop="approvalNotes">
                            <Input placeholder="审批意见" type="textarea" :autosize="{minRows:2,maxRows:5}" v-model='map.approvalNotes'></Input>
                        </FormItem>
                    </Col>
                </Row>
            </Form>
            <div slot="footer">
                <Button class='ivu-btn-save' @click="subView(map,1)">确定</Button>
                <Button class='ivu-btn-cancel' @click="model2=false;map={}">取消</Button>
            </div>
        </Modal>

        <Modal :transfer=false v-model="model4"  :width=900>
            <Tabs>
                <TabPane label="历史记录">
                    <Table ref='table1' border :columns="columns2" no-data-text="没有查询到相关数据！" style="margin-top: 0" :loading="loading2"
                           :data="history" width="100%"  :height="450" highlight-row stripe size="small"></Table>
                </TabPane>
                <TabPane label="流程图">
                    <div style="height: 450px; overflow-y: auto; overflow-x: auto">
                        <img :src="imgUrl" >
                    </div>
                </TabPane>
            </Tabs>
            <div slot="footer">
                <Button @click="model4=false" class="ivu-btn-save">关闭</Button>
            </div>
        </Modal>
    </Layout>
</template>

<script>
    import {Api} from '@/api/index.js'
    import {sessionStorage} from '../../../common/cacheUtils.js';
    var cascaderDom = () => import('@/components/cascader-dom.vue');
    import pageCommonFunction from '@/components/pageCommonFunction.js'
    export default {
        components:{
            cascaderDom
        },
        data(){
            return{
                ...this.createCommonDataField(),
                fileUrl:Api.interestedPartiesUserFile,
                downloadUrl:Api.downloadMongoFile,
                columns1: [
                    { title: '序号', width: 80, fixed: 'left', align: 'center', render: pageCommonFunction.indexColumnsRender.bind(this)},
                    {key: 'approval', title: '审批状态', align: 'center', minWidth: 90, render: (h, params) => {
                            return h('span', {style: {color: params.row.procinstState=='1'?'blue':params.row.procinstState=='2'?'red':params.row.procinstState=='3'?'green':'red'}},
                                params.row.procinstState=='1'?'待审批':params.row.procinstState=='2'?'审批退回':params.row.procinstState=='3'?'审批通过':params.row.procinstState=='5'?'流程终止':'待提交')
                        }},
                    {
                        title: '年度',
                        width: 80,
                        align: 'center',
                        key:'year',
                    },
                    {
                        title: '集团名称',
                        align: 'center',
                        key:'belongOrgName',
                        minWidth: 220,
                    },
                    {
                        title: '检查开始时间',
                        width: 120,
                        align: 'center',
                        key:'checkStartTime',
                        render: this.renderCellDate
                    },
                    {
                        title: '检查结束时间',
                        width: 120,
                        align: 'center',
                        key:'checkEndTime',
                        render: this.renderCellDate
                    },
                    {
                        title: '检查企业数量',
                        width: 100,
                        align: 'center',
                        key:'checkNumCompany',
                    },
                    {
                        title: '填报人',
                        width: 100,
                        align: 'center',
                        key:'createUserName'
                    },
                    {
                        title: '填报时间',
                        width: 120,
                        align: 'center',
                        key:'registranTime',
                        render: this.renderCellDate
                    },
                    {
                        title: '二级集团环保负责人',
                        minWidth: 120,
                        align: 'center',
                        key:'approvalUserName',
                    },
                    {
                        title: '集团审核人',
                        minWidth: 120,
                        align: 'center',
                        key:'aduitUserName', //approvalNotes
                        tooltip:true
                    },
                    // this.getActionColumns()
                    {
                        title: '操作',
                        key: 'action',
                        fixed: 'right',
                        width: 270,
                        align: 'center',
                        render: (h, params) => {
                            const enable = this.currentUser.loginId === this.Common.admin || this.currentUser.userId === params.row.createUserId ||this.currentUser.userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
                                ||this.currentUser.userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined;
                            return h('div', [
                                h('A', {
                                    props: {type: 'primary', size: 'small'},
                                    style: {fontSize: '14px',},
                                    on: {
                                        click: () => {
                                            this.viewData(params);
                                        }
                                    }
                                }, '详情'),
                                h('Divider', { props: { type: 'vertical' } }, ''),
                                h('A', {
                                    props: {type: 'primary', size: 'small'},
                                    style: {fontSize: '14px',
                                        color: (params.row.procinstId == null||params.row.procinstState=='5')&&enable?'':'#c5c8ce',
                                        pointerEvents:(params.row.procinstId == null||params.row.procinstState=='5')&&enable?'':'none'},
                                    on: {
                                        click: () => {
                                            if((params.row.procinstId == null||params.row.procinstState=='5')&&enable) {
                                                this.editData(params);
                                            }
                                        }
                                    }
                                }, '修改'),
                                 h('Divider', { props: { type: 'vertical' } }, ''),
                                h('A', {
                                    props: {type: 'primary', size: 'small'},
                                    style: {fontSize: '14px',
                                        color: (params.row.procinstState==0||params.row.procinstState=='5')&&enable?'red':'#c5c8ce',
                                        pointerEvents:(params.row.procinstState==0||params.row.procinstState=='5')&&enable?'':'none'},
                                    on: {
                                        click: () => {
                                            if((params.row.procinstState==0||params.row.procinstState=='5')&&enable) {
                                                this.deleteData(params);
                                            }
                                        }
                                    }
                                }, '删除'),
                                h('Divider', { props: { type: 'vertical' } }, ''),
                                h('A', {
                                    props: {type: 'primary', size: 'small'},
                                    style: {fontSize: '14px',
                                        color: (params.row.procinstState==0||params.row.procinstState=='5')&&enable?'':'#c5c8ce',
                                        pointerEvents:(params.row.procinstState==0||params.row.procinstState=='5')&&enable?'':'none'},
                                    on: {
                                        click: () => {
                                            if((params.row.procinstState==0||params.row.procinstState=='5')&&enable) {
                                                // params.row.approval=1
                                                this.subView(params.row);
                                            }
                                        }
                                    }
                                }, '上报'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('a', {
                                    props: {
                                        type: 'primary',
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: params.row.procinstId == null ? '#d0d0d0' : '',
                                        pointerEvents: params.row.procinstId == null ? 'none' : ''
                                    },
                                    on: {
                                        click: () => {
                                            this.imgUrl = Api.getFlowImg + '/' + params.row.procinstId
                                            this.showHistory(params.row);
                                        }
                                    }
                                },'流程图')
                            ]);
                        }
                    },
                ],
                ruleCustom : {
                    belongOrgId: [{ required: true, message: '  ', trigger: 'blur' }],
                    approvalUser: [{ required: true, message: ' ', trigger: 'blur' }],
                    aduitUser: [{ required: true, message: ' ', trigger: 'blur' }],
                    registrantPhone: [{
                        validator: (rule, value, callback) => {
                            if(!(/^1[3456789]\d{9}$/.test(this.dataToView.registrantPhone))){
                                callback(' ');
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'blur'
                    }],
                },
                // api
                queryUrl:Api.queryEvalSummary,
                deleteUrl:Api.deleteEvalSummary,
                updateUrl:Api.updateEvalSummary,
                saveUrl:Api.saveEvalSummary,

                model2:false,
                map:{},
                twoLevel:[],
                chargeList:[],
                aduitUserList:[],

                history:[],
                model4:false,
                loading2:false,
                imgUrl:"",
                columns2: [
                    {
                        type: 'index',
                        title: '序号',
                        width: 80,
                        align: 'center',
                    },
                    {
                        width: 180,
                        title: '审批时间',
                        key: 'endTime',
                        align: 'center',
                    },
                    {
                        width: 185,
                        title: '节点名称',
                        key: 'name',
                        align: 'center',
                    },
                    {
                        width: 120,
                        title: '审批人',
                        key: 'userName',
                        align: 'center'
                    },
                    {
                        width: 100,
                        title: '审批意见',
                        key: 'route',
                        align: 'center'
                    },
                    {
                        width: 200,
                        title: '备注',
                        key: 'opinions',
                        align: 'center'
                    },
                ],
            }
        },
        mounted() {
            this.dataToQuery.year1 = new Date()
            this.dataToQuery.year = new Date().getFullYear().toString()
            this.setTableHeight();
            this.query();
            this.selectSecGroupNames()
            this.selectChargeList(this.currentUser.twoLevelOrgId)
            this.$http.get(Api.queryRoleUser + "/" +"17744170d3c24383bd283fbe72f3d664", {params: {}}).then((res) => {
                this.aduitUserList=  res.data.data
            }).catch(e => {
                this.$Message.error("数据获取失败")
            });
        },
        methods:{
            ...pageCommonFunction,
            selectSecGroupNames(){
                this.$http.get(Api.quqeryTwoOrgInfo).then(res => {
                    this.twoLevel=res.data.data
                }).catch(e => {
                })
            },
            selectChargeList(twoLevel){
                this.$http.get(Api.queryRoleUser + "/" +"843197356dd443d099542d7ebe22b2be", {params: {twoLevel:twoLevel}}).then((res) => {
                    this.chargeList = res.data.data;
                }).catch(e => {
                    this.$Message.error("数据获取失败")
                });
            },
            deleteData(params) {
                this.deleteDateAjax(params);
            },
            query() {
                // if(this.dataToQuery.year) {
                //     this.dataToQuery.year = this.dataToQuery.year.getFullYear();
                // }
                this.queryAjax()
            },
            belongChange(value) {
                this.dataToView.belongOrgId = value.value
                this.dataToView.belongOrgName = value.label
                this.selectChargeList(value.value)
            },
            charge(value){
                this.dataToView.approvalUser = value.value;
                this.dataToView.approvalUserName = value.label;
            },
            subView(row,type){
                this.$Modal.confirm({
                    title: '提示',
                    content: '<p>是否要提交？</p>',
                    onOk: () => {
                        // this.$http.put(this.updateUrl, row).then((res) => {
                        //     this.$Message.info('提交成功')
                        //     this.query()
                        //     this.model2=false
                        // })
                        let map ={
                            workId: row.id,
                            createUserId: sessionStorage('userId').getObject('userId').userId,
                            userName: sessionStorage('userId').getObject('userId').userName,
                            key: 'evalSummary',
                            formKey: 'evalSummaryApproval',
                            user1: row.approvalUser,
                            user2: row.aduitUser
                        }
                        this.$http.post(Api.submit, map).then(function(res){
                            // this.sendMessage(row.approvalUser);
                            this.buttonLoading = false;
                            this.modal4 = false;
                            if(res.data.status == 200){
                                this.$Message.success({ content: '上报成功', duration: 4 });
                                this.query();
                            }else{
                                this.$Message.error({ content: res.data.msg, duration: 4 });
                            }
                        });
                    },
                    onCancel: () => {
                        this.query()
                        this.model2=false
                    }
                });
            },
            sendMessage(userId){
                let data = {userId: userId, content: "您有一条环境标准化现场审核验收总结需审批，请登录安全环保信息平台进行审批" };
                this.$http.post(Api.sendMessage, data);
            },
            submit(name) {
                if(this.dataToView.yearDate) {
                    this.dataToView.year = this.dataToView.yearDate.getFullYear();
                }
                this.submitAjax(name);
            },
            createEmptyDataToAdd() {
                return {
                    id:this.get_uuid(),
                    idFiles:[],
                    registranTime:new Date(),
                    checkNumCompany:0,
                    approval:0,
                    yearDate:new Date(),
                    createUserName:this.currentUser.userName,
                    aduitUser:this.aduitUserList.find(i=>i.userName==='谢辉')===undefined?'':this.aduitUserList.find(i=>i.userName==='谢辉').userId
                }
            },
            async beforeEditDialogOpen(data) {
                data.row.yearDate = new Date(data.row.year + '-01-01');
                this.selectChargeList(data.row.belongOrgId)

            },
            async afterDataToViewInit() {
                await this.getFiles('id');
            },
            showHistory(row) {
                this.model4 = true;
                this.loading2 = true;
                this.$http.get(Api.getHistory + '/' + row.procinstId, {params: {}}).then((res) => {
                    this.history = res.data;
                    this.loading2 = false;
                }).catch(e => {
                    this.$Message.error("数据获取失败")
                })
            },
        },
        watch:{
        },

    }
</script>

<style lang='css' scoped>
    .ivu-form-item {
        padding-right: 20px;
    }

    .query-form-el, .ivu-date-picker, .ivu-input-wrapper {
        width: 100%;
    }
</style>
